//
//  ProjectManagementViewController.m
//  Againstpoor
//
//  Created by 辰领科技 on 16/11/8.
//  Copyright © 2016年 yuf. All rights reserved.
//

#import "ProjectManagementViewController.h"
#import "ProjectManagementTableViewCell.h"
#import "ProjectTotalViewController.h"
static NSString *Indentifer;

@interface ProjectManagementViewController ()
<UITableViewDelegate,UITableViewDataSource> {
    NSInteger _totle;
}
@property (nonatomic,assign)   NSInteger    pageNO;

@property (weak, nonatomic) IBOutlet UILabel *titleLabel;

@property (weak, nonatomic) IBOutlet UIView *navView;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UILabel *BGLabel;
@property (weak, nonatomic) IBOutlet UILabel *slidingLabel;
@property (weak, nonatomic) IBOutlet UIButton *leftButton;
@property (weak, nonatomic) IBOutlet UIButton *rightButton;

@property (strong, nonatomic) NSMutableArray *array;
@property (strong, nonatomic) NSMutableDictionary *Dic;

@end

@implementation ProjectManagementViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (_type == 1) {
        _titleLabel.text = @"扶贫项目";
    } else if (_type == 2) {
        _titleLabel.text = @"扶贫资金";
    }
    [self.tableView.header beginRefreshing];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _array = [NSMutableArray array];
    _Dic = [NSMutableDictionary dictionary];
    _pageNO = 1;
    [self initViewLayout];
    [self addRefreshing];
}
- (void)initViewLayout{
    [self adaptiveViewLayout:self.view];
    [self adaptiveViewLayout:self.navView];
    
    _BGLabel.layer.masksToBounds = YES;
    _BGLabel.layer.cornerRadius = 18*VerticalRatio();
    _slidingLabel.layer.masksToBounds = YES;
    _slidingLabel.layer.cornerRadius = 15*VerticalRatio();
}

- (IBAction)back:(id)sender {
    [self backBtn];
}

#pragma mark -- 添加刷新数据
- (void)addRefreshing{
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self getprojectOne];
        int64_t delayInSeconds = 8.0;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [self.tableView.header endRefreshing];
        });
        self.pageNO = 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            [self getprojectTwo];
        });
    }];
    [_tableView.header beginRefreshing];
}
//加载更多数据
- (void)loadMoreData{
    if (self.array.count == _totle) {
        [self.tableView.footer endRefreshing];
    }else{
        self.pageNO = self.pageNO + 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            [self getprojectTwo];
        });
    }
}
#pragma mark - 扶贫项目 总的贫困村项目统计
- (void)getprojectOne {
    NSMutableDictionary * dic = [NSMutableDictionary dictionary];
    self.shareApi.delegate = self;
    [self.shareApi  requestOperationWithDic:dic withPath:F_getProjectCountryTotal withHttpType:@"POST" withTag:F_F_getProjectCountryTotal];
}
#pragma mark - 扶贫项目 按脱贫村区分项目
- (void)getprojectTwo {
    NSMutableDictionary * dic = [NSMutableDictionary dictionary];
    if (_leftButton.selected) {
        [dic setObject:@"1" forKey:@"type"];
    } else if (_rightButton.selected) {
        [dic setObject:@"2" forKey:@"type"];
    }
    [dic setObject:[NSString stringWithFormat:@"%d",_pageNO] forKey:@"pageNum"];
    [dic setObject:[NSString stringWithFormat:@"%d",PageSize] forKey:@"pageSize"];
    self.shareApi.delegate = self;
    [self.shareApi  requestOperationWithDic:dic withPath:F_getProjectCountry withHttpType:@"POST" withTag:F_F_getProjectCountry];
}

#pragma mark - 责任部门 && 乡镇（街道）
- (IBAction)button:(UIButton *)sender {
    if (sender == _leftButton) {
        _leftButton.selected = YES;
        _rightButton.selected = NO;
        [UIView animateWithDuration:0.1 animations:^{
            _slidingLabel.frame = flexibleFrame(CGRectMake(36, 66, 125, 30), NO);
        }];
    } else {
        _leftButton.selected = NO;
        _rightButton.selected = YES;
        [UIView animateWithDuration:0.1 animations:^{
            _slidingLabel.frame = flexibleFrame(CGRectMake(160, 66, 125, 30), NO);
        }];
    }
    [_tableView.header beginRefreshing];
}


#pragma mark - <UITableViewDelegate&&UITableViewDataSource>
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

//定义 UITableView cell 的个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _array.count+1;
}

//定义 UITableView cell 的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 200*VerticalRatio();
}

//定义 UITableView cell 展示的内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_type == 1) {
        Indentifer = @"tableviewCell";
    } else if (_type == 2) {
        Indentifer = @"tableviewCellOne";
    }
    ProjectManagementTableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:Indentifer];
    if (cell == nil) {
        cell= [[ProjectManagementTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:Indentifer];
        
    }
    for (UIView *view in cell.subviews) {
        if ([view isKindOfClass:[UILabel class]] ||[view isKindOfClass:[UIImageView class]]||[view isKindOfClass:[UIScrollView class]]||[view isKindOfClass:[UIButton class]]) {
            [view removeFromSuperview];
        }
    }
    
    if (_type == 1) {
        if (indexPath.row == 0) {
            cell.titleLabel.text = [NSString stringWithFormat:@"%@个贫困村",_Dic[@"NUMBER"]];
            [cell.planningbutton setTitle:[NSString stringWithFormat:@" 规划项目：%@个",_Dic[@"ALLTOTAL"]] forState:UIControlStateNormal];
            
            NSString * one = [Common stringFromData:_Dic[@"PROJECT1"]];
            NSMutableAttributedString * strOne = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"下达资金项目：%@个",one]];
            [strOne addAttribute:NSForegroundColorAttributeName value:kGetColor(182, 2, 1) range:NSMakeRange(7, one.length)];
            [cell.labelOne setAttributedText:strOne];
            NSString * two = [Common stringFromData:_Dic[@"PRESSTYPE1"]];
            NSMutableAttributedString * strtwo = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"未开工项目：%@个",two]];
            [strtwo addAttribute:NSForegroundColorAttributeName value:kGetColor(182, 2, 1) range:NSMakeRange(6, two.length)];
            [cell.labelTwo setAttributedText:strtwo];
            NSString * three = [Common stringFromData:_Dic[@"PRESSTYPE3"]];
            NSMutableAttributedString * strthree = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"已完工项目：%@个",three]];
            [strthree addAttribute:NSForegroundColorAttributeName value:kGetColor(182, 2, 1) range:NSMakeRange(6, three.length)];
            [cell.labelThree setAttributedText:strthree];
            NSString * four = [Common stringFromData:_Dic[@"PROJECT2"]];
            NSMutableAttributedString * strfour = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"未下达资金项目：%@个",four]];
            [strfour addAttribute:NSForegroundColorAttributeName value:kGetColor(182, 2, 1) range:NSMakeRange(8, four.length)];
            [cell.labelFour setAttributedText:strfour];
            NSString * five = [Common stringFromData:_Dic[@"PRESSTYPE2"]];
            NSMutableAttributedString * strfive = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"开工在建项目：%@个",five]];
            [strfive addAttribute:NSForegroundColorAttributeName value:kGetColor(182, 2, 1) range:NSMakeRange(7, five.length)];
            [cell.labelFive setAttributedText:strfive];
            NSString * six = [Common stringFromData:_Dic[@"PRESSTYPE4"]];
            NSMutableAttributedString * strsix = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"已验收项目：%@个",six]];
            [strsix addAttribute:NSForegroundColorAttributeName value:kGetColor(182, 2, 1) range:NSMakeRange(6, six.length)];
            [cell.labelSix setAttributedText:strsix];
            [cell.totalAmountButton setTitle:[NSString stringWithFormat:@" 规划投资总额：￥%@万",[Common stringFromData:_Dic[@"COUNT"]]] forState:UIControlStateNormal];
            [cell.arriveButton setTitle:[NSString stringWithFormat:@" 下达资金：￥%@万",[Common stringFromData:_Dic[@"PRICE1"]]] forState:UIControlStateNormal];
            [cell.notArriveButton setTitle:[NSString stringWithFormat:@" 下达资金：￥%@万",[Common stringFromData:_Dic[@"PRICE2"]]] forState:UIControlStateNormal];
        } else {
            NSDictionary *dic = _array[indexPath.row - 1];
            
            if ([dic.allKeys containsObject:@"ALLECIATION_TIME"]) {
                cell.titleLabel.text = [NSString stringWithFormat:@"%@年脱贫村", [Common stringFromData:dic[@"ALLECIATION_TIME"]]];
            } else {
                cell.titleLabel.text = [NSString stringWithFormat:@"年脱贫村"];
            }
            
            [cell.planningbutton setTitle:[NSString stringWithFormat:@" 规划项目：%@个",[Common stringFromData:dic[@"ALLTOTAL"]]] forState:UIControlStateNormal];
            
            NSString * one = [Common stringFromData:dic[@"PROJECT1"]];
            NSMutableAttributedString * strOne = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"下达资金项目：%@个",one]];
            [strOne addAttribute:NSForegroundColorAttributeName value:kGetColor(182, 2, 1) range:NSMakeRange(7, one.length)];
            [cell.labelOne setAttributedText:strOne];
            NSString * two = [Common stringFromData:dic[@"PRESSTYPE1"]];
            NSMutableAttributedString * strtwo = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"未开工项目：%@个",two]];
            [strtwo addAttribute:NSForegroundColorAttributeName value:kGetColor(182, 2, 1) range:NSMakeRange(6, two.length)];
            [cell.labelTwo setAttributedText:strtwo];
            NSString * three = [Common stringFromData:dic[@"PRESSTYPE3"]];
            NSMutableAttributedString * strthree = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"已完工项目：%@个",three]];
            [strthree addAttribute:NSForegroundColorAttributeName value:kGetColor(182, 2, 1) range:NSMakeRange(6, three.length)];
            [cell.labelThree setAttributedText:strthree];
            NSString * four = [Common stringFromData:dic[@"PROJECT2"]];
            NSMutableAttributedString * strfour = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"未下达资金项目：%@个",four]];
            [strfour addAttribute:NSForegroundColorAttributeName value:kGetColor(182, 2, 1) range:NSMakeRange(8, four.length)];
            [cell.labelFour setAttributedText:strfour];
            NSString * five = [Common stringFromData:dic[@"PRESSTYPE2"]];
            NSMutableAttributedString * strfive = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"开工在建项目：%@个",five]];
            [strfive addAttribute:NSForegroundColorAttributeName value:kGetColor(182, 2, 1) range:NSMakeRange(7, five.length)];
            [cell.labelFive setAttributedText:strfive];
            NSString * six = [Common stringFromData:dic[@"PRESSTYPE4"]];
            NSMutableAttributedString * strsix = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"已验收项目：%@个",six]];
            [strsix addAttribute:NSForegroundColorAttributeName value:kGetColor(182, 2, 1) range:NSMakeRange(6, six.length)];
            [cell.labelSix setAttributedText:strsix];
            if ([dic.allKeys containsObject:@"COUNT"]) {
                [cell.totalAmountButton setTitle:[NSString stringWithFormat:@" 规划投资总额：￥%@万",[Common stringFromData:dic[@"COUNT"]]] forState:UIControlStateNormal];
            } else {
                [cell.totalAmountButton setTitle:[NSString stringWithFormat:@" 规划投资总额：￥0万"] forState:UIControlStateNormal];
            }
            
            [cell.arriveButton setTitle:[NSString stringWithFormat:@" 下达资金：￥%@万",[Common stringFromData:dic[@"PRICE1"]]] forState:UIControlStateNormal];
            [cell.notArriveButton setTitle:[NSString stringWithFormat:@" 未下达资金：￥%@万",[Common stringFromData:dic[@"PRICE2"]]] forState:UIControlStateNormal];
        }
        
    } else if (_type == 2) {
        if (indexPath.row == 0) {
            cell.titleLabel.text = [NSString stringWithFormat:@"%@个贫困村",[Common stringFromData:_Dic[@"NUMBER"]]];
            [cell.planningbutton setTitle:[NSString stringWithFormat:@" 规划投资总额：￥%@万",[Common stringFromData:_Dic[@"COUNT"]]] forState:UIControlStateNormal];
            
            NSString * one = [Common stringFromData:_Dic[@"PRICE1"]];
            NSMutableAttributedString * strOne = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"下达资金：￥%@万",one]];
            [strOne addAttribute:NSForegroundColorAttributeName value:kGetColor(182, 2, 1) range:NSMakeRange(6, one.length)];
            [cell.arriveLabel setAttributedText:strOne];
            NSString * two = [Common stringFromData:_Dic[@"PRICE2"]];
            NSMutableAttributedString * strtwo = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"未下达资金：￥%@万",two]];
            [strtwo addAttribute:NSForegroundColorAttributeName value:kGetColor(182, 2, 1) range:NSMakeRange(7, two.length)];
            [cell.notArriveLabel setAttributedText:strtwo];
            
            [cell.totalAmountButton setTitle:[NSString stringWithFormat:@" 规划项目：%@个",_Dic[@"ALLTOTAL"]] forState:UIControlStateNormal];
            
            cell.labelOne.text = [NSString stringWithFormat:@"下达资金项目：%@个",[Common stringFromData:_Dic[@"PROJECT1"]]];
            cell.labelTwo.text = [NSString stringWithFormat:@"未开工项目：%@个",[Common stringFromData:_Dic[@"PRESSTYPE1"]]];
            cell.labelThree.text = [NSString stringWithFormat:@"已完工项目：%@个",[Common stringFromData:_Dic[@"PRESSTYPE3"]]];
            cell.labelFour.text = [NSString stringWithFormat:@"未下达资金项目：%@个",[Common stringFromData:_Dic[@"PROJECT2"]]];
            cell.labelFive.text = [NSString stringWithFormat:@"开工在建项目：%@个",[Common stringFromData:_Dic[@"PRESSTYPE2"]]];
            cell.labelSix.text = [NSString stringWithFormat:@"已验收项目：%@个",[Common stringFromData:_Dic[@"PRESSTYPE4"]]];
        } else {
            NSDictionary *dic = _array[indexPath.row - 1];
            
            if ([dic.allKeys containsObject:@"ALLECIATION_TIME"]) {
                cell.titleLabel.text = [NSString stringWithFormat:@"%@年脱贫村", [Common stringFromData:dic[@"ALLECIATION_TIME"]]];
            } else {
                cell.titleLabel.text = [NSString stringWithFormat:@"年脱贫村"];
            }
            
            if ([dic.allKeys containsObject:@"COUNT"]) {
                [cell.planningbutton setTitle:[NSString stringWithFormat:@" 规划投资总额：￥%@万",[Common stringFromData:dic[@"COUNT"]]] forState:UIControlStateNormal];
            } else {
                [cell.planningbutton setTitle:[NSString stringWithFormat:@" 规划投资总额：￥0万"] forState:UIControlStateNormal];
            }
            
            
            NSString * one = [Common stringFromData:dic[@"PRICE1"]];
            NSMutableAttributedString * strOne = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"下达资金：￥%@",one]];
            [strOne addAttribute:NSForegroundColorAttributeName value:kGetColor(182, 2, 1) range:NSMakeRange(6, one.length)];
            [cell.arriveLabel setAttributedText:strOne];
            NSString * two = [Common stringFromData:dic[@"PRICE2"]];
            NSMutableAttributedString * strtwo = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"未下达资金：￥%@",two]];
            [strtwo addAttribute:NSForegroundColorAttributeName value:kGetColor(182, 2, 1) range:NSMakeRange(7, two.length)];
            [cell.notArriveLabel setAttributedText:strtwo];

            [cell.totalAmountButton setTitle:[NSString stringWithFormat:@" 规划项目：%@个",[Common stringFromData:dic[@"ALLTOTAL"]]] forState:UIControlStateNormal];
            
            cell.labelOne.text = [NSString stringWithFormat:@"下达资金项目：%@个",[Common stringFromData:dic[@"PROJECT1"]]];
            cell.labelTwo.text = [NSString stringWithFormat:@"未开工项目：%@个",[Common stringFromData:dic[@"PRESSTYPE1"]]];
            cell.labelThree.text = [NSString stringWithFormat:@"已完工项目：%@个",[Common stringFromData:dic[@"PRESSTYPE3"]]];
            cell.labelFour.text = [NSString stringWithFormat:@"未下达资金项目：%@个",[Common stringFromData:dic[@"PROJECT2"]]];
            cell.labelFive.text = [NSString stringWithFormat:@"开工在建项目：%@个",[Common stringFromData:dic[@"PRESSTYPE2"]]];
            cell.labelSix.text = [NSString stringWithFormat:@"已验收项目：%@个",[Common stringFromData:dic[@"PRESSTYPE4"]]];
        }
        
        
    }
    
    return cell;
}

//定义 UITableView cell 点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"HomePageStoryboard" bundle:nil];
    ProjectTotalViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"ProjectTotal"];
    page.type = self.type;
    if (indexPath.row != 0) {
        page.time = [Common stringFromData:_array[indexPath.row-1][@"ALLECIATION_TIME"]];
    }
    [[Common getNavigation]pushViewController:page];
}

#pragma   mark---- GetADBanner Request Delegate

-(void)fetchDatabaseFinished:(NSMutableDictionary *)database withTag:(NSInteger)tag{
    [_tableView.header endRefreshing];
    if (tag==F_F_getProjectCountry) {
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                _totle = [database[@"total"] integerValue];
                if (_totle > PageSize) {
                    __weak __typeof(self) weakSelf = self;
                    if (!self.tableView.footer) {
                        // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
                        self.tableView.footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
                            [weakSelf loadMoreData];
                        }];
                    }
                }
                if (self.pageNO == 1) {
                    [self.array removeAllObjects];
                }
                
                NSArray *arr = database[@"rows"];
                for (id entity in arr) {
                    [self.array addObject:entity];
                }
                
                self.tableView.delegate = self;
                self.tableView.dataSource = self;
                [_tableView reloadData];
            });
            
        }else  {
        }
    } else if (tag==F_F_getProjectCountryTotal) {
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            _Dic = database[@"rows"][0];
            
            [self.tableView reloadData];
        }else  {
        }
    }
}

-(void)fetchDatabaseFailed:(NSError *)error message:(NSString *)message{
    
    [_tableView.header endRefreshing];
    [self dismissWaitDialog];
    
}

@end
